<!--李柯辰-->
<template>
  <div>
    <el-card shadow="hover" style="height: 200px">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="130px" class="demo-ruleForm">
        <el-row>
          <el-col :span="5">
            <el-form-item label="供应商" prop="supplierId">
              <el-select v-model="ruleForm.supplierId" placeholder="请选择">
                <el-option
                  v-for="item in supplierListOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="应付金额" prop="payable">
              <el-input v-model="ruleForm.amountPayable" disabled="disabled"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="实付金额" prop="paid">
              <el-input v-model="ruleForm.amountPaid"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="收货日期" prop="date">
              <el-date-picker v-model="ruleForm.purchaseDate" type="date" placeholder="选择时间" format="yyyy-MM-dd"
                              style="width: 100%;"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="15">
            <el-form-item label="备注" prop="remarks">
              <el-input v-model="ruleForm.remarks"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="是否付款" prop="isPaid">
              <el-select v-model="ruleForm.isPaid" placeholder="请选择">
                <el-option label="未付款" :value="0"/>
                <el-option label="已付款" :value="1"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item style="float: right">
          <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-table
      :data="this.ruleForm.tableData"
      height="500"
      style="width: 100%">
      <el-table-column>
        <el-table-column
          label="商品编码"
          prop="code">
        </el-table-column>
        <template slot="header" slot-scope="scope">
          <el-button size="mini" type="primary"
                     class="el-icon-circle-plus-outline"
                     @click="insertGoods()"
                     style="float: left">
            添加
          </el-button>
        </template>

      </el-table-column>
      <el-table-column>
        <el-table-column label="234" prop="name" disabled></el-table-column>
        <el-table-column label="商品型号" prop="model"></el-table-column>
        <el-table-column label="商品单位" prop="unit"></el-table-column>
        <el-table-column label="单价" prop="price"></el-table-column>
        <el-table-column label="数量" prop="num"></el-table-column>
        <el-table-column label="总金额" prop="total"></el-table-column>
        <el-table-column
          align="right">
          <template slot="header" slot-scope="scope">
            <el-input
              v-model="search"
              size="mini"
              placeholder="输入关键字搜索"/>
          </template>
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table-column>
    </el-table>

      <el-dialog title="添加商品" :visible.sync="dialogTableVisible">
        <el-table :data="gridData">
          <el-table-column property="id" label="id"></el-table-column>
          <el-table-column property="code" label="编码"></el-table-column>
          <el-table-column property="name" label="商品名称"></el-table-column>
          <el-table-column property="inventoryQuantity" label="库存数量"></el-table-column>
          <el-table-column property="lastPurchasingPrice" label="上次采购价格"></el-table-column>
          <el-table-column property="model" label="商品型号"></el-table-column>
          <el-table-column property="unit" label="单位"></el-table-column>
          <el-table-column property="producer" label="生产厂商"></el-table-column>
          <el-table-column property="purchasingPrice" label="平均采购价格"></el-table-column>
          <el-table-column property="saleTotal" label="商品金额"></el-table-column>
          <el-table-column property="sellingPrice" label="出售价格"></el-table-column>
          <el-table-column property="state" label="货物状态"></el-table-column>
          <el-table-column property="typeId" label="类别ID"></el-table-column>
          <el-table-column property="minNum" label="库存下限"></el-table-column>
          <el-table-column property="enable" label="是否启用" ></el-table-column>
          <el-table-column property="remarks" label="备注"></el-table-column>
          <el-table-column property="gmtCreate" label="数据创造时间"></el-table-column>
          <el-table-column property="gmtModified" label="数据最后修改时间"></el-table-column>
          <el-table-column  label="操作">
            <template slot-scope="scope">
                <el-button size="mini" type="danger" @click="loadSaleProductList(scope.row)">选择</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination align='center'
                       @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"
                       :current-page="page"
                       :page-sizes="[5,10,20,100]"
                       :page-size="pageSize"
                       layout="total, sizes, prev, pager, next, jumper"
                       :total="total">
        </el-pagination>
      </el-dialog>

    <el-dialog title="修改商品信息" :visible.sync="update">
      <el-form ref="form" :data="form" label-width="100px">
        <el-form-item label="商品编码">
        <el-input v-model="form.code"  width="20" disabled="disabled"></el-input>
        </el-form-item>
        <el-form-item label="商品名称">
          <el-input v-model="form.name" disabled="disabled"></el-input>
        </el-form-item>
        <el-form-item label="商品型号">
        <el-input v-model="form.model"  width="20" disabled="disabled"></el-input>
        </el-form-item>
        <el-form-item label="商品单位">
        <el-input v-model="form.unit"  width="20" disabled="disabled"></el-input>
        </el-form-item>
        <el-form-item label="单价">
        <el-input v-model="form.price"  width="20"></el-input>
        </el-form-item>
        <el-form-item label="数量">
        <el-input v-model="form.num" ></el-input>
        </el-form-item>
        <el-form-item label="总金额" style = "visibility: hidden">
        <el-input v-model="form.total" ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="" @click="update=false">取消</el-button>
        <el-button type="" @click="FormUpdate()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

export default {
  data() {
    return {
      pageSize:5,
      page:1,
      total:0,
      update:false,
      dialogTableVisible: false,
      //数据
      form:{},
      formLabelWidth: '120px',
      gridData: [],
      search: '',
      supplierListOptions: [],
      ruleForm: {
        tableData: [],
        supplierId: null,
        amountPayable: 0,
        amountPaid: 0,
        purchaseDate: '',
        remarks: '',
        isPaid: null,
      },
      rules: {
        supplierId: [
          {type: 'number', required: true, message: '请选择品牌', trigger: 'blur'},
        ],
        amountPayable: [
          {required: true, message: '请输入应付金额', trigger: 'blur'},
        ],
        amountPaid: [
          {required: true, message: '请输入实付金额', trigger: 'blur'},
        ],
        purchaseDate: [
          {type: 'date', required: true, message: '请输入日期', trigger: 'blur'},
        ],
        remarks: [
          {message: '请输入备注', trigger: 'blur'},
        ],
        isPaid: [
          {type: 'number', required: true, message: '请选择是否付款', trigger: 'blur'},
        ]
      }
    };
  },
  methods: {
    sum(){
      this.form.total = this.form.price * this.form.num;
    },
    //金额计算
    countAmountPayable() {
      let sum = 0;
      let tableData = this.ruleForm.tableData;
      for (let i = 0; i < tableData.length; i++) {
        sum = sum + tableData[i].total
      }
      this.ruleForm.amountPayable = sum;
      console.log(this.ruleForm.amountPayable);
    },
    handleCurrentChange(){

    },
    handleSizeChange(){

    },
    loadSaleProductList(row){
      for (let i = 0; i < this.ruleForm.tableData.length; i++) {
        let product =this.ruleForm.tableData[i];
        if(product.id==row.id){
          return;
        }
      }
      this.ruleForm.tableData.push(row);
      console.log(this.ruleForm.tableData);
      this.dialogTableVisible =false;
    },
    insertGoods(){
      let url = 'http://localhost:8887/goods/getHasInventoryQuantity' //?page='+this.page+'&pageSize='+this.pageSize;
      console.log('url = ' + url);
      // let stringify = this.qs.stringify(this.tableData);
      // console.log(stringify);
      this.axios
        .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
        .get(url ).then((response) => {
        let responseBody = response.data.data;
        console.log("wonn"+responseBody);
        // this.total=response.data.data.total;
        this.gridData=responseBody;
        console.log(this.gridData)
        this.dialogTableVisible =true;
      });
    },
    FormUpdate(){
      this.sum();
     this.countAmountPayable();
     this.update=false;
    },
    sub() {
      let total = 0;
      for (let i = 0; i < this.ruleForm.tableData.length; i++) {
        total += this.ruleForm.tableData[i].total;
      }
      this.ruleForm.amountPayable = total;
    },
    date() {
      const now = new Date();
      const year = now.getFullYear(); //得到年份
      let month = now.getMonth(); //得到月份
      let date = now.getDate(); //得到日期
      month = month + 1;
      month = month.toString().padStart(2, "0");
      date = date.toString().padStart(2, "0");
      return new Date(`${year}-${month}-${date}`);
    },
    handleEdit(index, row) {
      this.countAmountPayable();
      this.form=row;
      this.update= true;
    },
    handleDelete(ReturnGoods, row) {
      console.log(ReturnGoods, row);
      this.ruleForm.tableData.splice(ReturnGoods, 1);
      let message = '是否删除此退货商品';
      this.$confirm(message, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {

      }).catch(() => {
      });
    },

    backToPreStep() {
      this.$router.push('spu-add-new');
    },

    submitForm(formName) {
      console.log(this.ruleForm);
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.ruleForm.tableData == false) {
            this.$notify({
              title: '警告',
              message: '尚未选择进货商品',
              type: 'warning'
            });
            return;
          }
          console.log(this.ruleForm);
          // console.log(this.tableData);

          /*
          localStorage.getItem('jwt')
          */
          let url = 'http://localhost:8887/purchaseListGoods/save';
          console.log('url = ' + url);
          // let stringify = this.qs.stringify(this.tableData);
          // console.log(stringify);
          this.axios
            .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
            .post(url,this.ruleForm).then((response) => {
            let responseBody = response.data;
            if (responseBody.state == 20000) {
              this.ruleForm.brandName = responseBody.data.name;
              let ruleFormString = JSON.stringify(this.ruleForm);
              console.log('ruleFormString >>> ' + ruleFormString);
              localStorage.setItem('ruleForm', ruleFormString);
              this.$router.push('spu-add-new3');
            } else {
              this.$message.error(responseBody.message);
            }
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    supplierList() {
      let url = 'http://localhost:8887/supplier/getComboboxList';
      this.axios
        .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
        .get(url).then((response) => {
        let responseBody = response.data;
        this.supplierListOptions = responseBody.data;
        console.log(this.supplierListOptions)
        this.countAmountPayable();
      });
    }
  },
  mounted() {
    this.ruleForm.purchaseDate = this.date();
    this.supplierList();
    this.countAmountPayable();
    /*this.loadBrandList();
    this.loadLocalRuleForm();*/
  }
}
</script>
